package com.lkm.app_ui.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.util.Log;

import com.google.gson.JsonObject;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.HandleDialog;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.help.WifiUtils;
import com.lkm.app_ui.jz.util.JzUtil;
import com.lkm.app_ui.m.Imple.fun.FunModuleImple;
import com.lkm.app_ui.m.Imple.fun.RegBalanceTask;
import com.lkm.app_ui.m.Imple.steelyard_ser.SteelyardServerModuleSerialport;
import com.lkm.app_ui.m.Imple.sz_dataup.SZCalibrationInfoTask;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.netapi.AppApi;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.task2.DefaultTaskExecutor;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.task.ProgressData;
import com.lkm.frame.task.ProgressDataImpl;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.JsonP;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.URLHelp;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyarddata.SteelyardValue;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m.steelyardstatus.StatusInfo;
import com.lkm.market2_0.m.steelyardstatus.SteelyardStatusManagerModule;
import com.lkm.market2_0.netapi.Api;

import java.util.Locale;
import java.util.Map;


class WifiFragmentFun {
    private WifiFragment wifiFragment;

    public WifiFragmentFun(WifiFragment wifiFragment) {
        this.wifiFragment = wifiFragment;
        initWifiConnect();
    }

    public void onNumber(float number) {

        if (number == 0f) {
            if (CaptureBarcodeActivity.captureBarcodeActivity == null) {
                wifiFragment.goSacnQRView();
            }
        } else if (number == 1f) {
            regBalance();
        } else if (number == 11f) {

            upAD();
        } else if (number == 2f) {

            biaoding();
        } else if (number == 3f) {
            JzUtil.checkUpdateApp(false);
            FunModuleImple initAppModule = (FunModuleImple) AppConst.getModuleManager().peekModule(FunModule.class);
            if (initAppModule != null)
                initAppModule.checkVersionUp();
        } else if (number == 33f) {

            FunModuleImple initAppModule = (FunModuleImple) AppConst.getModuleManager().peekModule(FunModule.class);
            if (initAppModule != null)
                initAppModule.installApkIfNewDown();
        } else if (number == 4f) {


            android.os.Process.killProcess(android.os.Process.myPid());
        } else if (number == 5f) {
            RouterUINavigation.getInstance().showGoodsButton((BaseFragmentActivity) wifiFragment.getActivity());
            RouterUINavigation.getInstance().dismiss(wifiFragment);
        } else if (number == 6f) {
            RouterUINavigation.getInstance().showInfo((BaseFragmentActivity) wifiFragment.getActivity());
            RouterUINavigation.getInstance().dismiss(wifiFragment);
        }
//        else if ("fun_5".equals(v.getTag())) {


//        } else if ("fun_6".equals(v.getTag())) {


        else if (number == 7f) {

            setprinterMode("p-cm");
            wifiFragment.uiTips("设置打印机：p-cm");
        } else if (number == 77f) {

            setprinterMode("");
            wifiFragment.uiTips("设置打印机：新打印机");
        } else if (number == 8f) {
            loadPrintTemplate();
        } else if (number == 9f) {
            if (CaptureBarcodeActivity.captureBarcodeActivity != null)
                CaptureBarcodeActivity.captureBarcodeActivity.finish();
            else
                wifiFragment.closeUI();

        }
    }


    void regBalance() {
        if (wifiFragment.isExit()) return;
        SteelyardValue steelyardValue = getAndCheckSteelyardValue();
        if (steelyardValue != null) {
            RegBalanceTask regBalanceTask = RegBalanceTask.start(steelyardValue);
            wifiFragment.holdTaskCollection().add(regBalanceTask.getSerialNum());
            if (regBalanceTask != null) {
                regBalanceTask.addBackCall(new BackCallAdapter<String, Boolean>() {
                    @Override
                    public void onPreExecute(Task<?, String, Boolean> task) {
                        super.onPreExecute(task);
                        ViewUIHelp.showProgressBar(wifiFragment.getActivity(), "登记台秤(AD值)...", RegBalanceTask.class.getName());
                    }

                    @Override
                    protected void onEnd(Task<?, String, Boolean> task, Boolean aBoolean, boolean isCancel) {
                        super.onEnd(task, aBoolean, isCancel);
                        ViewUIHelp.disProgressBar(RegBalanceTask.class.getName());
                        if (!isCancel && aBoolean) {
                            wifiFragment.uiTips("登记台秤(AD值)成功。");
                        } else {
                            wifiFragment.uiTips("登记台秤(AD值)失败。");
                        }
                    }
                });
            }
        }

    }

    public void setprinterMode(String printerMode) {
        RunTimeData.printerMode = printerMode;
        AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("printerMode", RunTimeData.printerMode).commit();
    }

    private void setSerialport(String serialport) {
        RunTimeData.serialport = serialport;
        AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("serialport", RunTimeData.serialport).commit();


//            SteelyardServerModuleSerialport serverModule = (SteelyardServerModuleSerialport) AppConst.getModuleManager().peekModule(SteelyardServerModule.class);


    }


    public void onReadStr(String s) {


        if (s.trim().startsWith("WIFI:")) {
            String wificonfigStr = s.trim().substring(5);

            wificonfigStr = wificonfigStr.replaceAll(":", "=");
            wificonfigStr = wificonfigStr.replaceAll(";", "&");
            Map<String, String> wifiConfig = URLHelp.parserUrlToParams(wificonfigStr);
            String              wifiname   = wifiConfig.get("S");
            String              wifiPass   = wifiConfig.get("P");
            String              type       = wifiConfig.get("T");
            int                 passType   = WifiUtils.WIFICIPHER_NOPASS;

            if (!StringHelp.isEmpty(type)) {
                passType = type.contains("WPA") ? WifiUtils.WIFICIPHER_WPA : WifiUtils.WIFICIPHER_WEP;
                if (type.toLowerCase(Locale.ROOT).contains("nopass")) {
                    passType = WifiUtils.WIFICIPHER_NOPASS;
                }
            }

            if (!StringHelp.isEmpty(wifiname)) {
                wifiTask.connectWifi(wifiname, wifiPass, passType);
//                wifiFragment.uiTips(String.format("连接WiFi: %s %s %s",wifiname,wifiPass ,type));
                wifiFragment.uiTips(String.format("连接WiFi: %s", wifiname));
                return;
            }
        }


        if (s.trim().startsWith("{")) {

            JsonP jsonP = new JsonP(s);
            int   type  = -1;
            try {
                String tips = "";

                if (type == -1) {


                    String wifiname = jsonP.get("w").getAsString("");
                    String wifiPass = jsonP.get("p").getAsString("");
                    int    passType = jsonP.get("wpt").getAsInt(WifiUtils.WIFICIPHER_WPA);
                    if (!StringHelp.isEmpty(wifiname)) {

                        wifiTask.connectWifi(wifiname, wifiPass, passType);
                        tips += ("设置wifi：" + wifiname);
                    }


                    String screenAutoOff = jsonP.get("t").getAsString("");
                    //P.d("Bill->screenAutoOff:默认的" + RunTimeData.screenAutoOff);
                    //P.d("Bill-> screenAutoOff:获取前" + screenAutoOff);
                    if (!StringHelp.isEmpty(screenAutoOff)) {
                        RunTimeData.screenAutoOff = NumberHelp.toInt(screenAutoOff, RunTimeData.screenAutoOff);
                        AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putInt("screenAutoOff", RunTimeData.screenAutoOff).commit();

                        tips += ("，设置延迟休眠：" + (RunTimeData.screenAutoOff > 0 ? RunTimeData.screenAutoOff / 1000f : RunTimeData.screenAutoOff));
                        try {
                            //P.d("Bill-> " + tips);
                            //P.d("Bill->screenAutoOff:获取后" + RunTimeData.screenAutoOff);
                            Settings.System.putInt(AppConst.getApplication().getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int) RunTimeData.screenAutoOff);//15000

                        } catch (Exception e) {
                            e.printStackTrace();
                            AppUIHelp.tryShowTipsSHORT("不支持系统休眠，错误编码：ScreenLockManagerImpleModule");
                        }
                    }


//                    String ast_oid = jsonP.get("f").getAsString("");

//                    AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("ast_oid", RunTimeData.ast_oid).commit();


                    String isUpAD = jsonP.get("ad").getAsString("");
                    if ("1".equals(isUpAD)) {
                        tips += "，上报AD值";
                        upAD();
                    }


                    String hostApi = jsonP.get("h").getAsString("");
                    if (!StringHelp.isEmpty(hostApi)) {
                        boolean isSaveAPiSuccess = MyApplication.getInstance().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("tv_url", hostApi).commit();

                        tips += isSaveAPiSuccess ? "HostApi保存成功" : "HostApi保存失败";

                        if (!isSaveAPiSuccess) {
                            new HandleDialog().show(wifiFragment.getActivity(), "HostApi保存失败，请重试！！", OnSteelyardKeyEvent.KEYCODE_9, "关闭（按9）", null, false);
                        } else {
                            Api.host = hostApi;
                        }
                    }


                    String szhostApi = jsonP.get("szh").getAsString("");
                    if (!(szhostApi.length() == 0)) {
                        boolean isSaveAPiSuccess = MyApplication.getInstance().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("tv_szurl", szhostApi).putLong("tv_szurl_t", System.currentTimeMillis() / 1000).commit();

                        tips += isSaveAPiSuccess ? "数据上报地址保存成功（sz）" : "数据上报地址保存失败（sz）";
                        if (isSaveAPiSuccess) {
                            tips += "：" + szhostApi;
                        }

                        if (!isSaveAPiSuccess) {
                            new HandleDialog().show(wifiFragment.getActivity(), "数据上报地址保存失败，请重试！！（sz）", OnSteelyardKeyEvent.KEYCODE_9, "关闭（按9）", null, false);
                        } else {
                            RunTimeData.setSZHost(szhostApi);
                        }
                    }


                    String printerMode = jsonP.get("pm").getAsString("");
                    if (!StringHelp.isEmpty(printerMode)) {
                        setprinterMode(printerMode);
                        tips += ("，设置打印机：" + (printerMode));
                    }


                } else {

                }
                wifiFragment.uiTips(tips);
            } catch (Exception e) {
//                new Handler(Looper.getMainLooper()).
                wifiFragment.uiTips("设别到的数据无效");
            }

        } else {
            wifiFragment.uiTips("设别到非配置数据");
        }
    }


    WifiConnectTask wifiTask;

    private void initWifiConnect() {
        wifiTask = new WifiConnectTask();
        wifiTask.action();
        wifiTask.execTask();
        wifiTask.addBackCall(new BackCallAdapter<String, Boolean>() {
            @Override
            public void onProgresing(Task<?, String, Boolean> task, ProgressData<String> progressData) {
                super.onProgresing(task, progressData);

                String ssid = WifiUtils.getInstance().getSSID();
                String tips = "连接信息：";
                if (!StringHelp.isEmpty(ssid)) {
                    tips += "\n连接的wifi：" + ssid;
                    tips += "\nip地址：" + WifiUtils.getInstance().getWifiIP();
                    tips += "\n信道：" + WifiUtils.getInstance().getCurrentChannel();
                    tips += "\n信号5格：" + WifiUtils.getInstance().getCurWifiLevel();
                    tips += "\nmac地址：" + WifiUtils.getInstance().getLocalMacAddressNo();
                }

                wifiFragment.showContent(progressData.getData() + tips);

            }
        });
        wifiFragment.holdTaskCollection().add(wifiTask.getSerialNum());
    }

    private static class WifiConnectTask extends TaskAdapter<Void, String, Boolean> {

        public static String getTaskId() {
            return WifiConnectTask.class.getName();
        }


        public WifiConnectTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), getTaskId(), AppConst.getTaskManager2());
        }

        private WifiConnectTask.WifiReceiver wifiReceiver = null;

        private String wifiname, wifiPass;
        private int passType;

        public void connectWifi(String wifiname, String wifiPass, int passType) {
            this.wifiname = wifiname;
            this.wifiPass = wifiPass;
            this.passType = passType;
            if (WifiUtils.getInstance().isWifiEnable()) {
                con();
            } else {
                WifiUtils.getInstance().openWifi();
            }

        }

        private void con() {
            if (StringHelp.isEmpty(wifiname)) return;
            String wifiname_ = wifiname;
            String wifiPass_ = wifiPass;
            int    passType_ = passType;

            wifiname = "";
            wifiPass = "";
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    if (StringHelp.isEmpty(wifiPass_)) {
                        WifiUtils.getInstance().connectWifiNoPws(wifiname_);
                    } else
                        WifiUtils.getInstance().connectWifiPws(wifiname_, wifiPass_, passType_);
                }
            });
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);

            IntentFilter filter = new IntentFilter();
            filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            AppConst.getApplication().registerReceiver(wifiReceiver = new WifiConnectTask.WifiReceiver(), filter);
        }

        @Override
        public boolean interceptComplete(Task<Void, ?, Boolean> task, Boolean result) {
            try {
                AppConst.getApplication().unregisterReceiver(wifiReceiver);
            } catch (Exception e) {
            }

            return super.interceptComplete(task, result);
        }


        public class WifiReceiver extends BroadcastReceiver {
            private static final String TAG = "wifiReceiver";

            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
                    progressUpdate(new ProgressDataImpl<String>(0, 2, "wifi已经连接"));
                }

                if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                    int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);

                    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                        Log.i(TAG, "=== wifi断开");
                        progressUpdate(new ProgressDataImpl<String>(0, 2, "wifi已经断开"));
                    }
                    if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                        progressUpdate(new ProgressDataImpl<String>(0, 2, "wifi连接中"));
                    } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                        WifiInfo    wifiInfo    = wifiManager.getConnectionInfo();

                        progressUpdate(new ProgressDataImpl<String>(0, 2, "连接到网络" + wifiInfo.getSSID()));
                    }
                }

                if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                    int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                    if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
                        Log.i(TAG, "=== 系统关闭wifi");
                        progressUpdate(new ProgressDataImpl<String>(0, 2, "wifi被关闭"));
                    } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
                        Log.i(TAG, "=== 系统开启wifi");

                        con();
                        progressUpdate(new ProgressDataImpl<String>(0, 2, "wifi被打开"));
                    }
                }
            }
        }

    }


    private void upAD() {
        if (wifiFragment.isExit()) return;
        SteelyardValue steelyardValue = getAndCheckSteelyardValue();
        if (steelyardValue != null) {
            TaskHelp.cancelById(UpADTask.class.getName());
            Task task = new UpADTask();
            task.action();
            task.setParam(steelyardValue);
            task.execTask();
        }

    }


    private class UpADTask extends TaskAdapter<SteelyardValue, String, Boolean> {


        public UpADTask() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), UpADTask.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(wifiFragment.getActivity(), "提交AD值...", UpADTask.class.getName());
        }

        @Override
        public void doExecuting(SteelyardValue param) {
            super.doExecuting(param);
            mTaskExecutor.executorDoAsyncExecuting(new Runnable() {
                @Override
                public void run() {
                    ResponEntity<Void> responEntity = ResponEntity.fromJson(AppApi.upAD(param, UpADTask.this), null, "");
                    complete(responEntity.isSuccess());

                }
            });
        }

        @Override
        public void onFinish(Boolean aBoolean) {
            super.onFinish(aBoolean);
            ViewUIHelp.disProgressBar(UpADTask.class.getName());
            if (aBoolean) {
                wifiFragment.uiTips("登记AD成功。");
            } else {
                wifiFragment.uiTips("登记AD失败。");
            }

        }

        @Override
        public void onCancel() {
            super.onCancel();
            ViewUIHelp.disProgressBar(UpADTask.class.getName());
        }
    }


    private void loadPrintTemplate() {
        if (wifiFragment.isExit()) return;
        TaskHelp.cancelById(LoadPrintTemplate.class.getName());
        Task task = new LoadPrintTemplate();
        task.action();
        task.setParam(null);
        task.execTask();

    }

    private class LoadPrintTemplate extends TaskAdapter<Void, String, ResponEntity<String>> {
        public String getTaskId() {
            return LoadPrintTemplate.class.getName();
        }

        public LoadPrintTemplate() {
            super(new DefaultTaskExecutor(AppConst.getTaskExecutor(), true), LoadPrintTemplate.class.getName(), AppConst.getTaskManager2());
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
            ViewUIHelp.showProgressBar(wifiFragment.getActivity(), "拉取打印模板...", getTaskId());
        }

        @Override
        public void doExecuting(Void param) {
            super.doExecuting(param);
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    ResponEntity<String> responEntity = ResponEntity.fromJson(AppApi.loadPrintTemplate(LoadPrintTemplate.this), String.class, "");
                    if (responEntity.isSuccess()) {
                        AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("orderPrintTemplate", responEntity.getData()).commit();
                    }
                    complete(responEntity);
                }
            });
        }

        @Override
        public boolean onInterceptEnd(boolean isCancel, ResponEntity<String> result) {
            ViewUIHelp.disProgressBar(getTaskId());
            return super.onInterceptEnd(isCancel, result);
        }

        @Override
        public void onFinish(ResponEntity<String> aBoolean) {
            super.onFinish(aBoolean);
            wifiFragment.uiTips(aBoolean.isSuccess() ? "拉取打印模板成功。" : "拉取打印模板失败。");
            if (aBoolean.isSuccess()) {
                RunTimeData.orderPrintTemplate = aBoolean.getData();
            }
        }
    }


    public void biaoding() {


        SteelyardValue steelyardValue = getAndCheckSteelyardValue();
        if (steelyardValue == null) return;

        OrderEntity.GoodEntity goodEntity = getAndCheckWeightChangeGood();
        if (goodEntity == null) return;

        SZCalibrationInfoTask task = new SZCalibrationInfoTask(RunTimeData.steelyardInfo, steelyardValue, goodEntity);
        task.action();
        task.execTask();
        task.addBackCall(new BackCallAdapter<Object[], String>() {
            @Override
            protected void onEnd(Task<?, Object[], String> task, String s, boolean isCancel) {
                super.onEnd(task, s, isCancel);
                if (wifiFragment.isExit()) return;
                if ("".equals(s) && !isCancel) {
                    wifiFragment.uiTips("提交成功");
                } else {
                    wifiFragment.uiTips("提交失败" + (s == null ? "，无网络" : ""));
                }
            }
        });

    }


    private OrderEntity.GoodEntity getAndCheckWeightChangeGood() {
        OrderEntity.GoodEntity goodEntity = null;
        try {
            SteelyardDataModule dataModule = AppConst.getModuleManager().loadModule(SteelyardDataModule.class);
            goodEntity = dataModule.getCurWeightChangeGood(RunTimeData.steelyardInfo.getSteelyardMac());
        } catch (Exception e) {
        }

        if (goodEntity == null) {
            wifiFragment.showTipsDialog("暂无称重信息，请确定称体正常后重试。");
//            new HandleDialog().show(getActivity(), "暂无称重信息，请确定称体正常后重试。", OnSteelyardKeyEvent.KEYCODE_9, "关闭（按9）", null, false, true);
        }
        return goodEntity;
    }


    private SteelyardValue getAndCheckSteelyardValue() {
        SteelyardValue steelyardValue = null;
        try {
//            SteelyardDataModule dataModule = AppConst.getModuleManager().loadModule(SteelyardDataModule.class);
            steelyardValue = RunTimeData.getSteelyardValue();// dataModule.getSteelyardValue(RunTimeData.steelyardInfo.getSteelyardMac());

            StatusInfo                   statusInfo          = null;
            SteelyardStatusManagerModule statusManagerModule = (SteelyardStatusManagerModule) AppConst.getModuleManager().peekModule(SteelyardStatusManagerModule.class);
            if (statusManagerModule != null) {
                statusInfo = statusManagerModule.getStatusInfoBySteelyardMac(RunTimeData.steelyardInfo.getSteelyardMac());
            }
            if (statusInfo != null) {
                steelyardValue.exit_factory_id = statusInfo.getNumno();
            }

        } catch (Exception e) {
        }

        if (steelyardValue == null) {
            wifiFragment.showTipsDialog("暂无AD信息，请确定称体正常，重新启动整个设备");
//            new HandleDialog().show(getActivity(), "暂无AD信息，请确定称体正常，重新启动整个设备", OnSteelyardKeyEvent.KEYCODE_9, "关闭（按9）", null, false, true);
        }
        return steelyardValue;
    }

}
